package com.hawthorn.admin.service.sysjob.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hawthorn.admin.feign.jobService.CmsJobFeignService;
import com.hawthorn.admin.feign.jobService.OmsJobFeignService;
import com.hawthorn.admin.feign.jobService.RmsJobFeignService;
import com.hawthorn.admin.feign.jobService.TmsJobFeignService;
import com.hawthorn.admin.repository.SysJobMapper;
import com.hawthorn.admin.service.sysjob.SysJobService;
import com.hawthorn.component.constant.DicConstant;
import com.hawthorn.component.constant.FormatConstant;
import com.hawthorn.component.utils.bean.Map2ObjUtil;
import com.hawthorn.platform.exception.BizCode;
import com.hawthorn.platform.model.po.SysJobPO;
import com.hawthorn.platform.service.TransResultService;
import com.hawthorn.platform.utils.iassert.AssertMyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>todo 定时配置servce</p>
 * @author: andy.ten@tom.com | xukaixing@hotmail.com
 * @created: 2022/8/6 09:16
 * @version v1.0.1
 * @copyright: Copyright (c)  andyten
 */
@Service
public class SysJobServiceImpl implements SysJobService
{

  @Autowired
  private TransResultService transResultService;
  @Autowired
  private SysJobMapper sysJobMapper;

  @Autowired
  OmsJobFeignService omsJobFeignService;
  @Autowired
  CmsJobFeignService cmsJobFeignService;
  @Autowired
  RmsJobFeignService rmsJobFeignService;
  @Autowired
  TmsJobFeignService tmsJobFeignService;

  private HashMap<String, String> getTransHash()
  {
    HashMap<String, String> transHash = new HashMap<>();
    transHash.put("bizType", "dic|ywlx");
    transHash.put("status", "dic|yxzt");
    transHash.put("isSuccess", "dic|sf");
    transHash.put("isPause", "dic|sf");
    transHash.put("createTime", "date|" + FormatConstant.SIMPLE_DATE_TIME_FORMAT);

    return transHash;
  }


  /**
   * <p>todo 查询定时任务</p>
   * @param: page
   * @param: conditions
   * @return: com.baomidou.mybatisplus.core.metadata.IPage<java.util.Map < java.lang.String, java.lang.Object>>
   * @author: andy.ten@tom.com | xukaixing@hotmail.com
   * @date: 2022/8/6 09:17
   * @version: 1.0.1
   * Modification History:
   * Date         Author          Version            Description
   * -----------------------------------------------------------
   * 2022/8/6    andy.ten        v1.0.1             init
   */
  @Override
  public IPage<Map<String, Object>> findJobs(Page<Map<String, Object>> page, String conditions)
  {
    // 设置排序
    OrderItem oi = new OrderItem();
    oi.setColumn("create_time");
    oi.setAsc(true);
    List<OrderItem> al = page.getOrders();
    al.add(oi);
    page.setOrders(al);
    return transResultService.transResult(sysJobMapper.findJobs(page, conditions), getTransHash());
  }

  @Override
  public IPage<Map<String, Object>> findJobLogsById(Page<Map<String, Object>> page, String conditions)
  {
    // 设置排序
    OrderItem oi = new OrderItem();
    oi.setColumn("create_time");
    oi.setAsc(false);
    List<OrderItem> al = page.getOrders();
    al.add(oi);
    page.setOrders(al);
    return transResultService.transResult(sysJobMapper.findJobLogsById(page, conditions), getTransHash());
  }

  /**
   * <p>todo 新增定时任务</p>
   * @param: param
   * @return: java.util.Map<java.lang.String, java.lang.Object>
   * @author: andy.ten@tom.com | xukaixing@hotmail.com
   * @date: 2022/8/9 13:00
   * @version: 1.0.1
   * Modification History:
   * Date         Author          Version            Description
   * -----------------------------------------------------------
   * 2022/8/9    andy.ten        v1.0.1             init
   */
  @Override
  public Map<String, Object> saveJob(Map<String, Object> param)
  {
    SysJobPO sysJobPO = Map2ObjUtil.toObject(param, SysJobPO.class);
    AssertMyUtil.notNull(sysJobPO, BizCode.VARIABLE_NOT_NULL, "sysJobPO");
    // 判断是否已存在
    Integer jobIsExist = sysJobMapper.findJobByName(sysJobPO.getJobName());
    if (jobIsExist != 0)
    {
      AssertMyUtil.errMsg("定时任务已存在.");
    }

    sysJobMapper.save(sysJobPO);

    // todo: 创建job
    String modelName = sysJobPO.getModel();
    if (modelName.contains(".tms"))
    {
      tmsJobFeignService.addJob(sysJobPO);
    } else if (modelName.contains(".cms"))
    {
      cmsJobFeignService.addJob(sysJobPO);
    } else if (modelName.contains(".oms"))
    {
      omsJobFeignService.addJob(sysJobPO);
    } else if (modelName.contains(".rms"))
    {
      rmsJobFeignService.addJob(sysJobPO);
    }

    return transResultService.transResult(sysJobPO.toMaps(), getTransHash());
  }

  /**
   * <p>todo 更新job</p>
   * @param: id
   * @param: param
   * @return: java.util.Map<java.lang.String, java.lang.Object>
   * @author: andy.ten@tom.com | xukaixing@hotmail.com
   * @date: 2022/8/9 13:03
   * @version: 1.0.1
   * Modification History:
   * Date         Author          Version            Description
   * -----------------------------------------------------------
   * 2022/8/9    andy.ten        v1.0.1             init
   */
  @Override
  public Map<String, Object> updateJob(Long id, Map<String, Object> param)
  {
    AssertMyUtil.notNull(id, BizCode.METHOD_ARGS_NOTNULL, "id");
    SysJobPO sysJobPO = sysJobMapper.selectById(id);
    String oriCronExp = sysJobPO.getCronExpression();
    Map2ObjUtil.toObject(param, sysJobPO);
    String cronExp = sysJobPO.getCronExpression();
    sysJobMapper.updateById(sysJobPO);

    // todo: 更新job的定时参数
    String modelName = sysJobPO.getModel();
    if (modelName.contains(".tms"))
    {
      if (!cronExp.equals(oriCronExp))
        tmsJobFeignService.updateJobCron(sysJobPO);
    } else if (modelName.contains(".cms"))
    {
      if (!cronExp.equals(oriCronExp))
        cmsJobFeignService.updateJobCron(sysJobPO);
    } else if (modelName.contains(".oms"))
    {
      if (!cronExp.equals(oriCronExp))
        omsJobFeignService.updateJobCron(sysJobPO);
    } else if (modelName.contains(".rms"))
    {
      if (!cronExp.equals(oriCronExp))
        rmsJobFeignService.updateJobCron(sysJobPO);
    }
    return transResultService.transResult(sysJobPO.toMaps(), getTransHash());
  }

  /**
   * <p>todo 恢复计划任务</p>
   * @param: param
   * @return: void
   * @author: andy.ten@tom.com | xukaixing@hotmail.com
   * @date: 2022/8/9 13:05
   * @version: 1.0.1
   * Modification History:
   * Date         Author          Version            Description
   * -----------------------------------------------------------
   * 2022/8/9    andy.ten        v1.0.1             init
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void resumeJob(Long id)
  {
    SysJobPO sysJobPO = sysJobMapper.selectById(id);

    UpdateWrapper uw = new UpdateWrapper<>();
    sysJobPO.setStatus(Integer.parseInt(DicConstant.YXBS_01));
    uw.eq("id", id);
    sysJobMapper.update(sysJobPO, uw);

    // todo: 更新job的定时参数
    String modelName = sysJobPO.getModel();
    if (modelName.contains(".tms"))
    {
      tmsJobFeignService.resumeJob(sysJobPO);
    } else if (modelName.contains(".cms"))
    {
      cmsJobFeignService.resumeJob(sysJobPO);
    } else if (modelName.contains(".oms"))
    {
      omsJobFeignService.resumeJob(sysJobPO);
    } else if (modelName.contains(".rms"))
    {
      rmsJobFeignService.resumeJob(sysJobPO);
    }

  }

  /**
   * <p>todo 暂停计划任务</p>
   * @param: param
   * @return: void
   * @author: andy.ten@tom.com | xukaixing@hotmail.com
   * @date: 2022/8/9 13:06
   * @version: 1.0.1
   * Modification History:
   * Date         Author          Version            Description
   * -----------------------------------------------------------
   * 2022/8/9    andy.ten        v1.0.1             init
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void pauseJob(Long id)
  {
    SysJobPO sysJobPO = sysJobMapper.selectById(id);
    UpdateWrapper uw = new UpdateWrapper<>();
    sysJobPO.setStatus(Integer.parseInt(DicConstant.YXBS_02));
    uw.eq("id", id);
    sysJobMapper.update(sysJobPO, uw);

    // todo: 更新job的定时参数
    String modelName = sysJobPO.getModel();
    if (modelName.contains(".tms"))
    {
      tmsJobFeignService.pauseJob(sysJobPO);
    } else if (modelName.contains(".cms"))
    {
      cmsJobFeignService.pauseJob(sysJobPO);
    } else if (modelName.contains(".oms"))
    {
      omsJobFeignService.pauseJob(sysJobPO);
    } else if (modelName.contains(".rms"))
    {
      rmsJobFeignService.pauseJob(sysJobPO);
    }

  }

  /**
   * <p>todo 立即运行计划任务</p>
   * @param: param
   * @return: void
   * @author: andy.ten@tom.com | xukaixing@hotmail.com
   * @date: 2022/8/9 13:06
   * @version: 1.0.1
   * Modification History:
   * Date         Author          Version            Description
   * -----------------------------------------------------------
   * 2022/8/9    andy.ten        v1.0.1             init
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void runJobNow(Long id)
  {
    SysJobPO sysJobPO = sysJobMapper.selectById(id);

    // todo: 更新job的定时参数
    String modelName = sysJobPO.getModel();
    if (modelName.contains(".tms"))
    {
      tmsJobFeignService.runJobNow(sysJobPO);
    } else if (modelName.contains(".cms"))
    {
      cmsJobFeignService.runJobNow(sysJobPO);
    } else if (modelName.contains(".oms"))
    {
      omsJobFeignService.runJobNow(sysJobPO);
    } else if (modelName.contains(".rms"))
    {
      rmsJobFeignService.runJobNow(sysJobPO);
    }
  }
}
